package com.hmyd.hmyd_android.shop;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLDecoder;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.AppBasic;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.DtoInfoNoPage;
import com.hmyd.hmyd_android.dto.InfoDto;
import com.hmyd.hmyd_android.dto.MyOrderDetail;
import com.hmyd.hmyd_android.ui.BasicActivity;
import com.hmyd.hmyd_android.utils.MyToast;
import com.hmyd.hmyd_android.utils.Utils;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 订单详情
 * 
 * @author wangk
 * 
 */
@ContentView(R.layout.activity_order_detail)
public class OrderDetailsActivity extends BasicActivity implements
		OnClickListener {
	private Context mContext;
	private LinearLayout mGoodsListContent;
	private LayoutInflater inflater;
	private static final int ORDER_DETAIL = 1;
	private final int CONFIRM = 3;
	private String id;
	private MyOrderDetail myOrderDetail;

	private TextView mTvOrderNum;
	private TextView mTvState;
	private TextView mTvTime;
	private TextView mTvGenZhong;
	private TextView mTvName;
	private TextView mTvAddress;
	private TextView mTvRemark;
	private TextView mTvTotal;

	private Button mBtnConfirm;

	@ViewInject(R.id.home_title_txt)
	private TextView home_title_txt;
	@ViewInject(R.id.home_title)
	private View home_title;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	private void initViews() {

		String stateString = "";
		stateString = getIntent().getStringExtra("state");

		mContext = this;
		mTvOrderNum = (TextView) findViewById(R.id.order_num);
		mTvState = (TextView) findViewById(R.id.tv_state);
		mTvTime = (TextView) findViewById(R.id.tv_time);
		mTvGenZhong = (TextView) findViewById(R.id.tv_genzhong);
		mTvName = (TextView) findViewById(R.id.tv_name);
		mTvAddress = (TextView) findViewById(R.id.tv_address);
		mTvRemark = (TextView) findViewById(R.id.tv_remark);
		mTvTotal = (TextView) findViewById(R.id.tv_total);

		mBtnConfirm = (Button) findViewById(R.id.confirm);
		mBtnConfirm.setOnClickListener(this);
		mBtnConfirm.setVisibility(View.GONE);

		mGoodsListContent = (LinearLayout) findViewById(R.id.layout_goods_lists);
		inflater = LayoutInflater.from(mContext);

		if (stateString.equals("Processing")) {
			mTvState.setText("处理中");
			mTvGenZhong.setText("处理中");
			mBtnConfirm.setVisibility(View.VISIBLE);
			mBtnConfirm.setEnabled(false);
			mBtnConfirm
					.setBackgroundResource(R.drawable.confirm_receive_unactive);
		} else if (stateString.equals("Delivery")) {
			mTvState.setText("发货中");
			mTvGenZhong.setText("发货中");
			mBtnConfirm.setVisibility(View.VISIBLE);
			mBtnConfirm.setEnabled(true);
			mBtnConfirm
					.setBackgroundResource(R.drawable.confirm_receive_selector);
		} else if (stateString.equals("Treat")) {
			mTvState.setText("待处理");
			mTvGenZhong.setText("待处理");
			mBtnConfirm.setVisibility(View.VISIBLE);
			mBtnConfirm.setEnabled(false);
			mBtnConfirm
					.setBackgroundResource(R.drawable.confirm_receive_unactive);
		} else if (stateString.equals("Completed")) {
			mTvState.setText("已完成");
			mTvGenZhong.setText("已完成");
			mBtnConfirm.setVisibility(View.GONE);
		} else if (stateString.equals("Return")) {
			mTvState.setText("退换货");
			mTvGenZhong.setText("退换货");
			mBtnConfirm.setVisibility(View.GONE);
		} else {
			mTvState.setText("处理中");
			mTvGenZhong.setText("处理中");
			mBtnConfirm.setVisibility(View.VISIBLE);
			mBtnConfirm.setEnabled(false);
			mBtnConfirm
					.setBackgroundResource(R.drawable.confirm_receive_unactive);
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		RequestParams params = new RequestParams();
		params.addBodyParameter("itemId", id);
		onRequest(ORDER_DETAIL, UrlConstant.ORDER_DETAIL, HttpMethod.GET,
				params);
	}

	@Override
	public void onPostSuccess(int postId, String result) {
		Gson gson = new Gson();
		switch (postId) {
		case ORDER_DETAIL:
			Type type1 = new com.google.common.reflect.TypeToken<DtoInfoNoPage<MyOrderDetail>>() {
			}.getType();
			DtoInfoNoPage<MyOrderDetail> dtoInfoNoPage2 = gson.fromJson(result, type1);
			if(dtoInfoNoPage2 != null) {
				myOrderDetail = dtoInfoNoPage2.data;
			}
			if(dtoInfoNoPage2.suc != 1011) {
				MyToast.showHMToast(OrderDetailsActivity.this, false,
						"拉取订单详情失败");
			}
			setDatas();
			break;
		case CONFIRM:
			java.lang.reflect.Type type3 = new TypeToken<DtoInfoNoPage<InfoDto>>() {
			}.getType();
			DtoInfoNoPage<InfoDto> dtoInfoNoPage1 = gson.fromJson(result, type3);
			if(dtoInfoNoPage1.suc == 1011) {
				mBtnConfirm.setVisibility(View.GONE);
				mTvState.setText("已完成");
				mTvGenZhong.setText("已完成");
				MyToast.showHMToast(OrderDetailsActivity.this, true, "恭喜兑换成功");
			} else {
				MyToast.showHMToast(OrderDetailsActivity.this, false,
						dtoInfoNoPage1.errmsg);
			}
			break;
		default:
			break;
		}
	}

	private void setDatas() {
		mTvOrderNum.setText(myOrderDetail.ordernum);
		mTvState.setText(myOrderDetail.state);
		mTvTime.setText(Utils.getDateString(Long
				.parseLong(myOrderDetail.createdTime) * 1000) + "");
		mTvName.setText("收货人         " + myOrderDetail.addressee + "    "
				+ myOrderDetail.cellPhoneNumber);
		// 判断如果是直辖市，不显示省份
		if (myOrderDetail.province.trim().equals(myOrderDetail.city.trim())) {
			mTvAddress.setText(myOrderDetail.city + myOrderDetail.area
					+ myOrderDetail.address);
		} else {
			mTvAddress.setText(myOrderDetail.province + myOrderDetail.city
					+ myOrderDetail.area + myOrderDetail.address);
		}
		try {
			mTvRemark
					.setText(URLDecoder.decode(myOrderDetail.remarks, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// state：Processing(处理中)、Delivery（发货中）、Treat（待处理）、Completed（已完成）、Return（退换货）
		if (myOrderDetail.state.equals("Processing")) {
			mTvState.setText("处理中");
			mTvGenZhong.setText("处理中");
		} else if (myOrderDetail.state.equals("Delivery")) {
			mTvState.setText("发货中");
			mTvGenZhong.setText("发货中");
		} else if (myOrderDetail.state.equals("Treat")) {
			mTvState.setText("待处理");
			mTvGenZhong.setText("待处理");
		} else if (myOrderDetail.state.equals("Completed")) {
			mTvState.setText("已完成");
			mTvGenZhong.setText("已完成");
			mBtnConfirm.setVisibility(View.GONE);
		} else if (myOrderDetail.state.equals("Return")) {
			mTvState.setText("退换货");
			mTvGenZhong.setText("退换货");
			mBtnConfirm.setVisibility(View.GONE);
		}

		int total = 0;
		mGoodsListContent.removeAllViews();
		for (int i = 0; i < myOrderDetail.records.size(); i++) {

			total = total + myOrderDetail.records.get(i).presentPrice
					* myOrderDetail.records.get(i).number;

			View view = inflater.inflate(R.layout.view_goods_lists_item, null);
			ImageView imageView = (ImageView) view.findViewById(R.id.iv_goods);
			TextView name = (TextView) view.findViewById(R.id.tv_goods_name);
			TextView price = (TextView) view.findViewById(R.id.tv_goods_price);
			TextView num = (TextView) view.findViewById(R.id.tv_num);

			imageView.setScaleType(ScaleType.FIT_XY);
			ImageLoader.getInstance().displayImage(
					myOrderDetail.records.get(i).icon, imageView);
			name.setText(myOrderDetail.records.get(i).title);
			price.setText(myOrderDetail.records.get(i).presentPrice + "");
			num.setText("x" + myOrderDetail.records.get(i).number);

			mGoodsListContent.addView(view);
			if (i == myOrderDetail.records.size() - 1) {
				View line = view.findViewById(R.id.line);
				line.setVisibility(View.INVISIBLE);
			}
		}
		mTvTotal.setText(total + "");

	}

	@OnClick({R.id.confirm})
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.confirm:
			RequestParams params = new RequestParams();
			params.addBodyParameter("itemId", id);
			onRequest(CONFIRM, UrlConstant.ORDER_COMFIRN, HttpMethod.POST,
					params);
			break;
		default:
			break;
		}

	}

	@Override
	protected void setParams() {
		initViews();
		id = getIntent().getStringExtra("id");
		home_title.setOnTouchListener(touch);
		home_title_txt.setText("订单详情");
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			AppBasic.getInstance().finishCurrentActivity();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void leftButton() {
		AppBasic.getInstance().finishCurrentActivity();
	}

	@Override
	protected void rightButton() {

	}

	@Override
	public void onPostFailure(int postId, String msg) {
		// TODO Auto-generated method stub

	}
}
